#!/usr/bin/env python
import re
import os
import sys
import commands
from optparse import OptionParser

filepath = os.path.abspath(os.path.dirname(__file__))
scriptpath = os.path.dirname(filepath)
sys.path.append(scriptpath)

from config import DATA_PATH
SIGNAL_NAME = 'Fpz-Cz'
def autoCoverterFrame(filename):
    ## filefname is consisted with 'name(\w)-Hypnogram.edf'
    abs_filename = os.path.join(DATA_PATH, filename)
    if not os.path.exists(abs_filename):
        print "file %s doesn't exist"% abs_filename
        sys.exit(1)
    if not filename.endswith('-Hypnogram.edf'):
        print "file format error"
        print "the file should be '-Hypnogram.edf' file"
        sys.exit(1)

    basefilename = filename.split('-')[0]
    datafilename = basefilename[:-1] + '0-PSG.edf'
    print datafilename

    abs_datafilename = os.path.join(DATA_PATH, datafilename)
    if not os.path.exists(abs_datafilename):
        print "file %s doesn't exist"% abs_datafilename
        sys.exit(1)
    # -Hypnogram.edf is usually only one line
    # the 512 byte is header then comes the data
    # the data is \+(startseconds)\x15(duration secondes)\x14Sleep stage (stage name[W|1|2|3|4|R])
    # the data can be splited by '\x14\x00'
    abs_filename = os.path.join(DATA_PATH, filename)
    Hypnogramfile = open(abs_filename, 'r')
    lines = Hypnogramfile.readlines()
    
    if len(lines) == 1:
        line = lines[0]
    else:
        print "warning"
        print lines
        line = lines[0]

    data = line[512:]
    stage_list = data.split('\x14\x00')
    PATTERN = re.compile(r'\+(\d+)\x15(\d+)\x14Sleep stage (\w)')

    for stage in stage_list: 
        match = PATTERN.match(stage)
        if match:
            startseconds = match.group(1)
            startframe = int(startseconds) / 30 
            duration = match.group(2)
            count = int(duration) / 30
            sleep_type = match.group(3)
            cmd = 'python converterEDF.py -f %s -s %s -r %s -c %s -t %s'\
            % (datafilename, SIGNAL_NAME, startframe, count, sleep_type)
            print cmd
            status, output = commands.getstatusoutput(cmd)
            if status != 0:
                print output
                print "Fail to converter Frame"
                sys.exit(1)
    print "autoConverterFrame Successfully"

def main():
    usage = "./autoConverterFrame.py -f filename"
    parser = OptionParser(usage = usage)
    
    parser.add_option("-f", "--file", dest="filename",
                      help="data file name")
    (options,_) = parser.parse_args()

    if not options.filename: 
        print "please input filename"
        parser.print_help()
        sys.exit(1)
    
    filename = options.filename    
    autoCoverterFrame(filename)
    sys.exit(0)

if __name__ == '__main__':
    main()